package zent

import (
	"log"
	"strconv"
	"studygo/sp/a/zinx/ziface"
)

type MsgHandler struct {
	Apis map[uint32]ziface.IRouter
}

func NewMsgHandler() *MsgHandler {
	return &MsgHandler{
		Apis: make(map[uint32]ziface.IRouter),
	}
}

func (m *MsgHandler) DoMsgHandler(request ziface.IRequest) {
	//1 从其中找到MsgID
	handler, ok := m.Apis[request.GetMsgID()]
	if !ok {
		log.Println("api MsgId =", request.GetMsgID(), " is not found! need register!")
		return
	}
	//2 根据 对应的 router 业务 调用
	handler.PreHandler(request)
	handler.Handler(request)
	handler.PostHandler(request)
}

func (m *MsgHandler) AddRouter(msgId uint32, router ziface.IRouter) {
	//1 如果当前msg绑定的API 已经存在，
	if _, ok := m.Apis[msgId]; ok {
		panic("msgid 已经存在" + strconv.Itoa(int(msgId)))
	}

	//
	m.Apis[msgId] = router
	log.Println("Add api MsgId=", msgId, " succ!")
}
